package com.yxq.mdt.app.modules.search.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.orhanobut.hawk.Hawk;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.wuhenzhizao.titlebar.widget.CommonTitleBar;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.application.IntentHelper;
import com.yxq.mdt.app.base.BaseActivity;
import com.yxq.mdt.app.constant.RouteTable;
import com.yxq.mdt.app.modules.search.bean.SearchBean;
import com.yxq.mdt.app.modules.search.bean.SearchGroupBean;
import com.yxq.mdt.app.modules.search.bean.SearchTopicBean;
import com.yxq.mdt.app.modules.search.bean.SearchUserBean;
import com.yxq.mdt.app.modules.search.model.SearchModel;
import com.yxq.mdt.app.modules.search.prestener.ISearchContract;
import com.yxq.mdt.app.modules.search.prestener.SearchPresenter;
import com.yxq.mdt.app.modules.socialcontact.model.MainSocialContactModel;
import com.yxq.mdt.app.modules.socialcontact.ui.activity.CircleTheHomepageAc;
import com.yxq.mdt.app.modules.socialcontact.ui.activity.SocialPersonalHomepageAc;
import com.yxq.mdt.app.modules.socialcontact.ui.activity.SocialStateDetailsAc;
import com.yxq.mdt.app.net.ApiModel;
import com.yxq.mdt.app.utils.GridSpacingItemDecoration;
import com.yxq.mdt.app.utils.MediaPlayerHelper;
import com.yxq.mdt.app.widgets.tagview.Tag;
import com.yxq.mdt.app.widgets.tagview.TagView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jzvd.Jzvd;

/**
 * @author L
 * @time
 * @describe 搜索-社区
 */
@Route(path = RouteTable.ROUTER_ACTIVITY_SEARCH_COMMUNITY)
public class SearchCommunityActivity extends BaseActivity<SearchPresenter> implements ISearchContract.View {

    @BindView(R.id.search_tag_view)
    TagView mTagView;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    SearchGoodsListAdapter searchGoodsListAdapter;
    @BindView(R.id.search_tv_delete_his)
    TextView searchTvDeleteHis;
    @BindView(R.id.search_layout_his)
    RelativeLayout searchLayoutHis;
    String searchKey;
    int searchType = 0;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    SearchUserListAdapter searchUserListAdapter;
    SearchGroupListAdapter searchGroupListAdapter;
    SearchTopicListAdapter searchTopicListAdapter;

    @Override
    public int getLayoutId() {
        return R.layout.activity_search_community;
    }

    @Override
    public void initView() {
        mPresenter = new SearchPresenter(this, new SearchModel());
        ARouter.getInstance().inject(this);
        mCommonTitleBar.setListener((v, action, extra) -> {
            if (action == CommonTitleBar.ACTION_LEFT_BUTTON) {
                finish();
            } else if (action == CommonTitleBar.ACTION_SEARCH_SUBMIT) {
                if (TextUtils.isEmpty(mCommonTitleBar.getSearchKey()) && !TextUtils.isEmpty(mCommonTitleBar.getCenterSearchEditText().getHint().toString()) && !"搜索您感兴趣的内容".equals(mCommonTitleBar.getCenterSearchEditText().getHint().toString())) {
                    search(mCommonTitleBar.getCenterSearchEditText().getHint().toString());
                    return;
                }
                search(mCommonTitleBar.getSearchKey());
            } else if (action == CommonTitleBar.ACTION_RIGHT_TEXT) {
                if (TextUtils.isEmpty(mCommonTitleBar.getSearchKey()) && !TextUtils.isEmpty(mCommonTitleBar.getCenterSearchEditText().getHint().toString())) {
                    search(mCommonTitleBar.getCenterSearchEditText().getHint().toString());
                    return;
                }
                search(mCommonTitleBar.getSearchKey());
            }
        });
        mCommonTitleBar.getCenterSearchEditText().addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                search(mCommonTitleBar.getSearchKey());
            }
        });
        recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
        searchGoodsListAdapter = new SearchGoodsListAdapter(R.layout.layout_item_goods_list_ver_layout, null);
        recyclerView.setAdapter(searchGoodsListAdapter);
        recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, 8, false));
        searchGoodsListAdapter.setEmptyView(R.layout.layout_empty_view, recyclerView);
        searchGoodsListAdapter.isUseEmpty(false);

    }

    /**
     * 搜索
     *
     * @param searchKey 关键字
     */
    private void search(String searchKey) {
        if (TextUtils.isEmpty(searchKey)) {
            return;
        }
        searchLayoutHis.setVisibility(View.GONE);
        saveHisSearchTag(searchKey);
        List<String> searchTypeList = new ArrayList<>();
        searchTypeList.add(searchKey);
        searchTypeList.add(searchKey);
        searchTypeList.add(searchKey);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        SearchTypeListAdapter searchTypeListAdapter = new SearchTypeListAdapter(R.layout.layout_item_search_type_list, searchTypeList);
        recyclerView.setAdapter(searchTypeListAdapter);
        searchTypeListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                showLoadingDialog();
                switch (position) {
                    case 0://搜索用户
                        searchType = 0;
                        recyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
                        searchUserListAdapter = new SearchUserListAdapter(R.layout.layout_item_search_user_list, null);
                        recyclerView.setAdapter(searchUserListAdapter);
                        searchUserListAdapter.setEmptyView(R.layout.layout_empty_view, recyclerView);
                        searchUserListAdapter.isUseEmpty(false);
                        searchUserListAdapter.setOnItemClickListener((adapter1, view1, position1) -> {
                            Intent intent = new Intent(mActivity, SocialPersonalHomepageAc.class);
                            intent.putExtra("userId", searchUserListAdapter.getItem(position1).getUserId());
                            startActivity(intent);
                        });
                        refreshLayout.setOnRefreshListener(refreshLayout -> {
                            page = 1;
                            mPresenter.searchGsUser(searchKey, page, 20);
                        });
                        refreshLayout.setOnLoadMoreListener(refreshLayout -> {
                            page++;
                            mPresenter.searchGsUser(searchKey, page, 20);
                        });
                        mPresenter.searchGsUser(searchKey, 1, 20);
                        break;
                    case 1://搜索圈子
                        searchType = 1;
                        recyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
                        searchGroupListAdapter = new SearchGroupListAdapter(R.layout.layout_item_search_group_list, null);
                        recyclerView.setAdapter(searchGroupListAdapter);
                        searchGroupListAdapter.setEmptyView(R.layout.layout_empty_view, recyclerView);
                        searchGroupListAdapter.isUseEmpty(false);
                        searchGroupListAdapter.setOnItemClickListener((adapter1, view1, position1) -> {
                            Intent intent = new Intent(mActivity, CircleTheHomepageAc.class);
                            intent.putExtra("id", searchGroupListAdapter.getItem(position1).getId());
                            intent.putExtra("CircleName", searchGroupListAdapter.getItem(position1).getGroupname());
                            startActivity(intent);
                        });
                        refreshLayout.setOnRefreshListener(refreshLayout -> {
                            page = 1;
                            mPresenter.searchGroup(searchKey, page, 20);
                        });
                        refreshLayout.setOnLoadMoreListener(refreshLayout -> {
                            page++;
                            mPresenter.searchGroup(searchKey, page, 20);
                        });
                        mPresenter.searchGroup(searchKey, 1, 20);
                        break;
                    case 2://搜索内容
                        searchType = 2;
                        recyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
                        searchTopicListAdapter = new SearchTopicListAdapter(R.layout.layout_item_search_topic_list, null);
                        recyclerView.setAdapter(searchTopicListAdapter);
                        searchTopicListAdapter.setEmptyView(R.layout.layout_empty_view, recyclerView);
                        searchTopicListAdapter.isUseEmpty(false);
                        searchTopicListAdapter.setOnItemClickListener((adapter1, view1, position1) -> {
                            Intent intent = new Intent(mActivity, SocialStateDetailsAc.class);
                            intent.putExtra("topicId", searchTopicListAdapter.getItem(position1).getId());
                            startActivity(intent);
                        });
                        searchTopicListAdapter.setOnItemChildClickListener((adapter12, view12, position12) -> {
                            switch (view12.getId()) {
                                case R.id.group_lint:
                                    Intent it = new Intent(mActivity, CircleTheHomepageAc.class);
                                    it.putExtra("id", searchTopicListAdapter.getItem(position12).getGroupId());
                                    it.putExtra("CircleName", searchTopicListAdapter.getItem(position12).getGsName());
                                    startActivity(it);
                                    break;
                            }
                        });
                        recyclerView.addOnChildAttachStateChangeListener(new RecyclerView.OnChildAttachStateChangeListener() {
                            @Override
                            public void onChildViewAttachedToWindow(@NonNull View view) {
                            }

                            @Override
                            public void onChildViewDetachedFromWindow(@NonNull View view) {
                                try {
                                    Jzvd jzvd = view.findViewById(R.id.item_social_video_player);
                                    if (jzvd != null && Jzvd.CURRENT_JZVD != null && jzvd.jzDataSource.containsTheUrl(Jzvd.CURRENT_JZVD.jzDataSource.getCurrentUrl())) {
                                        if (Jzvd.CURRENT_JZVD != null && Jzvd.CURRENT_JZVD.screen != Jzvd.SCREEN_FULLSCREEN) {
                                            Jzvd.releaseAllVideos();
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                            @Override
                            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                                super.onScrollStateChanged(recyclerView, newState);
                                if (searchTopicListAdapter.countDownTimer != null) {
                                    searchTopicListAdapter.countDownTimer.onFinish();
                                    MediaPlayerHelper.pause();
                                }
                            }
                        });
                        refreshLayout.setOnRefreshListener(refreshLayout -> {
                            page = 1;
                            mPresenter.searchTopic(searchKey, page, 20);
                        });
                        refreshLayout.setOnLoadMoreListener(refreshLayout -> {
                            page++;
                            mPresenter.searchTopic(searchKey, page, 20);
                        });
                        mPresenter.searchTopic(searchKey, 1, 20);
                        break;
                }

            }
        });

    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        loadHisSearchTags();
    }

    /**
     * 保存搜索记录关键字至本地
     *
     * @param tag 关键字
     */
    private void saveHisSearchTag(String tag) {
        if (TextUtils.isEmpty(tag)) {
            return;
        }
        String search = Hawk.get("search-comm", null);
        List<String> keys = null;
        if (search != null) {
            keys = JSON.parseArray(search, String.class);
        }
        if (keys == null) {
            keys = new ArrayList<>();
        }
        //判断是否重复 重复不保存
        if (keys.contains(tag)) {
            return;
        }
        keys.add(tag);
        //最大保存10条记录
        if (keys.size() >= 11) {
            keys.remove(0);//移除第一条记录
        }
        Hawk.put("search-comm", JSON.toJSONString(keys));
    }

    /**
     * 读取本地保存的搜索历史记录关键字
     *
     * @return
     */
    private List<String> getHisSearchTags() {
        String search = Hawk.get("search-comm", null);
        if (TextUtils.isEmpty(search)) {
            return null;
        }
        List<String> keys = JSON.parseArray(search, String.class);
        return keys;
    }

    /**
     * 清空历史记录
     */
    private void clearHisCache() {
        mTagView.removeAllTags();
        searchLayoutHis.setVisibility(View.GONE);
        Hawk.delete("search-comm");
    }

    /**
     * 加载搜索历史
     */
    private void loadHisSearchTags() {
        //先清除所有搜索记录
        mTagView.removeAllTags();
        List<String> keys = getHisSearchTags();
        //默认显示第一条搜索记录
        mCommonTitleBar.getCenterSearchEditText().setHint((keys != null && keys.size() > 0) ? keys.get(keys.size() - 1) : "搜索您感兴趣的内容");
        if (keys == null) {
            return;
        }
        for (int i = 0; i < keys.size(); i++) {
            Tag tag = new Tag(keys.get(i));
            tag.tagTextColor = getResources().getColor(R.color.color_font_black);
            tag.layoutColor = getResources().getColor(R.color.bg_gray);
            tag.layoutColorPress = getResources().getColor(R.color.gray);
            tag.radius = 10f;
            tag.tagTextSize = 14f;
            tag.layoutBorderSize = 1f;
            tag.layoutBorderColor = getResources().getColor(R.color.bg_gray);
            tag.isDeletable = false;
            mTagView.addTag(tag);
        }
        mTagView.setOnTagClickListener((position, tag) -> mCommonTitleBar.getCenterSearchEditText().setText(tag.text));
        //有数据才显示清空按钮以及搜索历史提示
        if (keys.size() > 0) {
            searchLayoutHis.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onLoadSuccess(SearchBean searchBean) {
        hideLoadingDialog();
        hideSoftKeyBoard();
        searchGoodsListAdapter.setNewData(searchBean.getList());
        searchGoodsListAdapter.setOnItemClickListener((adapter, view, position) -> {
            //跳转商品详情
            Bundle bundle = new Bundle();
            bundle.putString("id", searchGoodsListAdapter.getItem(position).getId());
            IntentHelper.arouter(RouteTable.ROUTER_ACTIVITY_GOODS_DETAIL, bundle);
        });
        searchGoodsListAdapter.isUseEmpty(!(searchGoodsListAdapter.getData().size() > 0));
    }

    @Override
    public void onLoadFailed(String err) {
        hideLoadingDialog();
        ToastUtils.showShort(err);
    }

    @Override
    public void onLoadUserSuccess(SearchUserBean searchUserBean) {
        hideLoadingDialog();
        refreshLayout.finishLoadMore();
        refreshLayout.finishRefresh();
        if (page == 1) {
            searchUserListAdapter.setNewData(searchUserBean.getList());
        } else {
            if (searchUserBean.getList() != null && searchUserBean.getList().size() != 0) {
                searchUserListAdapter.addData(searchUserBean.getList());
            } else {
                refreshLayout.finishLoadMoreWithNoMoreData();
            }
        }

        searchUserListAdapter.isUseEmpty(!(searchUserListAdapter.getData().size() > 0));
    }

    @Override
    public void onLoadUserFailed(String err) {
        hideLoadingDialog();
        refreshLayout.finishLoadMore();
        refreshLayout.finishRefresh();
    }

    @Override
    public void onLoadGroupSuccess(SearchGroupBean searchGroupBean) {
        hideLoadingDialog();
        refreshLayout.finishLoadMore();
        refreshLayout.finishRefresh();
        if (page == 1) {
            searchGroupListAdapter.setNewData(searchGroupBean.getList());
        } else {
            if (searchGroupBean.getList() != null && searchGroupBean.getList().size() != 0) {
                searchGroupListAdapter.addData(searchGroupBean.getList());
            } else {
                refreshLayout.finishLoadMoreWithNoMoreData();
            }
        }

        searchGroupListAdapter.isUseEmpty(!(searchGroupListAdapter.getData().size() > 0));
    }

    @Override
    public void onLoadGroupFailed(String err) {
        hideLoadingDialog();
        refreshLayout.finishLoadMore();
        refreshLayout.finishRefresh();
    }

    @Override
    public void onLoadTopicSuccess(SearchTopicBean searchTopicBean) {
        hideLoadingDialog();
        refreshLayout.finishLoadMore();
        refreshLayout.finishRefresh();
        if (page == 1) {
            searchTopicListAdapter.setNewData(searchTopicBean.getList());
        } else {
            if (searchTopicBean.getList() != null && searchTopicBean.getList().size() != 0) {
                searchTopicListAdapter.addData(searchTopicBean.getList());
            } else {
                refreshLayout.finishLoadMoreWithNoMoreData();
            }
        }

        searchTopicListAdapter.isUseEmpty(!(searchTopicListAdapter.getData().size() > 0));
    }

    @Override
    public void onLoadTopicFailed(String err) {
        hideLoadingDialog();
        refreshLayout.finishLoadMore();
        refreshLayout.finishRefresh();
    }

    @OnClick(R.id.search_tv_delete_his)
    public void onViewClicked() {
        clearHisCache();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Jzvd.releaseAllVideos();
    }
}
